require 'digest'

class User < ActiveRecord::Base

  has_many :original_results
  has_many :pre_original_results
  has_and_belongs_to_many :stests, :join_table => "users_surveys", :class_name => "Survey"
  has_many :test_records
  has_many :surveys
  has_many :temp_users ,:foreign_key => "org_id"
  has_many :pre_test_records
  has_and_belongs_to_many :tests, :join_table => "orgs_surveys", :foreign_key => "org_id" ,:class_name => "Survey"

  validates_presence_of :username
  validates_uniqueness_of :username
  validates_length_of :password, :in => 6..20, :on => :create

  attr_accessor :password_confirmation
  #validates_confirmation_of :password
  
  def password
    @password
  end
  
  def password=(pwd)
    @password=pwd
    return if pwd.blank?
    create_new_salt
    self.passwordconf=User.encrypted_passwed(self.password, self.salt)
  end 
  
  def self.authenticate(name, passwd)
    user = self.find_by_username(name)
    if user
     e_passwd=encrypted_passwed(passwd, user.salt)
      if user.passwordconf != e_passwd
        user =nil 
      end
    end 
    user
  end

    
  def self.search(search, page)  
    paginate :per_page => 10, :page => page,  
    :conditions => ['username like ?', "%#{search}%"],  
    :order => 'id'  
  end

  def self.info_completed?(id)
    user = self.find_by_id(id)
    return user.is_complete == USER_INFO_COMPLETED ? true : false
  end

  def tested?(test)
    logger.info "Processing in user.tested>>>>>>>>>>>>>>>>"
    self.stests.include?(test)
  end

  def just_test(test)
    unless tests.include? test
      stests << test
    end
  end


  def create_new_salt
    self.salt=self.object_id.to_s+rand.to_s
  end

  #批量添加试用机构
  def self.generate_orgs
    User.transaction do
      (1..10).each do
        org = User.new
        org.name = "机构试用帐号"
        org.username = rendom_str(6)
        pass = rendom_str(6)
        org.password = pass
        org.password_confirmation = pass
        org.pass = pass
        org.user_type = 'org'
        org.account_num = 100
        org.save

        ur_update(org.id, 3)
        add_surveys_for_org(org)
      end
    end
  end

  def self.rendom_str(num)
     @str=""
     for i in 1..num
      if i%2==0
         @str += (97+rand(26)).chr.to_s
      else
        @str +=rand(10).to_s
      end
     end
     @str
  end
  
  protected
  def self.encrypted_passwed(password, salt)
    string_to_hash = "#{password}xinjiayuan#{salt}"
    Digest::SHA1.hexdigest(string_to_hash)
  end
  
  def validate_on_create
    if self.password != self.password_confirmation
      errors.add(:password_confirmation, "两次输入的密码不一致")
    end
  end

  #赋予机构用户的角色
  def self.ur_update(u_id, r_id)

    temp_ur = UserRole.find_by_sql("select id from user_roles where user_id= #{u_id} and  role_id = #{r_id}")
    if temp_ur.length == 0
      UserRole.add(u_id.to_s, r_id.to_s)
    else
      UserRole.del(u_id.to_s, r_id.to_s)
    end
  end

  #给机构试用帐号给量表
  def self.add_surveys_for_org(org)

    params = Hash.new
    params[:org] = Hash.new
    params[:org][:test_ids] = [37, 41, 54, 84, 94, 99, 100]

    org.update_attributes(params[:org])
  end
end
